package model;

import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import util.Tools;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;

public class LoadDAO implements OrderDAO {

    @Autowired
    Tools tools;

    public String ewbCount(Date end, int interval, String site) {
        String baseUrl = "http://202.120.117.179:8090/centerload/load?";

        if (!tools.getId2name().has(site)) {
            if (tools.getName2id().has(site)) {
                site = tools.getName2id().getString(site);
            } else {
                return new JSONArray().toString();
            }
        }

        Date start = tools.getStartTime(end, interval);
        HashMap<String, String> result = tools.acquireData(baseUrl, start, end, interval, site, null, null);

        String[] dates = result.keySet().toArray(new String[]{});
        Arrays.sort(dates);
        JSONArray jsonArray = new JSONArray();
        for (String date : dates) {
            JSONObject temp = new JSONObject();
            JSONObject data = new JSONObject(result.get(date));
            temp.put("weight", data.get("weight"));
            temp.put("num", data.get("pieces"));
            temp.put("date", date);
            jsonArray.put(temp);
        }

        return jsonArray.toString();
    }

    public String attendance(Date end, int interval, String site) {
        String loadbaseUrl = "http://202.120.117.179:8090/centerload/scanman?";
        String unloadbaseUrl = "http://202.120.117.179:8090/centerunload/scanman?";
        if (!tools.getId2name().has(site)) {
            if (tools.getName2id().has(site)) {
                site = tools.getName2id().getString(site);
            } else {
                return new JSONArray().toString();
            }
        }

        Date start = tools.getStartTime(end, interval);
        ArrayList<String> urls = new ArrayList<String>();
        urls.add(loadbaseUrl);
        urls.add(unloadbaseUrl);
        ArrayList<HashMap<String, String>> results = tools.acquireMultiData(urls, start, end, interval, site, null, null);
        HashMap<String, String> loadresult = results.get(0);
        HashMap<String, String> unloadresult = results.get(1);
//        HashMap<String, String> loadresult = tools.acquireData(loadbaseUrl, start, end, interval, site, null, null);
//        HashMap<String, String> unloadresult = tools.acquireData(unloadbaseUrl, start, end, interval, site, null, null);
        String[] dates = loadresult.keySet().toArray(new String[]{});
        Arrays.sort(dates);
        JSONArray jsonArray = new JSONArray();
        for(String date: dates) {
            JSONObject temp = new JSONObject();
            JSONArray loaddata = new JSONArray(loadresult.get(date));
            JSONArray unloaddata = new JSONArray(unloadresult.get(date));
            int loadCount = 0;
            int unloadCount = 0;
            for(Object f : loaddata) {
                JSONObject j = (JSONObject)f;
                if(j.getInt("pieces") > 0) {
                    loadCount++;
                }
            }
            for(Object f : unloaddata) {
                JSONObject j = (JSONObject)f;
                if(j.getInt("pieces") > 0) {
                    unloadCount++;
                }
            }
            temp.put("loadNum", loadCount);
            temp.put("unloadNum", unloadCount);
            temp.put("date", date);
            jsonArray.put(temp);
        }
        return jsonArray.toString();
    }

    public String goodsType(Date end, int interval, String site) {
        String baseUrl = "http://202.120.117.179:8090/ewb/load?";
        if (!tools.getId2name().has(site)) {
            if (tools.getName2id().has(site)) {
                site = tools.getName2id().getString(site);
            } else {
                return new JSONArray().toString();
            }
        }


        Date start = tools.getStartTime(end, interval);
        String[] goodsType = {"MiNi小包", "标准快运", "易碎品（MiNi小包）"};
        String[] colors = {"#003366", "#4cabce", "#006699", "#e5323e"};
        ArrayList<String> result = tools.acquireTypeData(baseUrl, start, end, site, goodsType.length);

        JSONArray jsonArray = new JSONArray();
        for(int i = 0; i < result.size(); i++) {
            JSONObject json = new JSONObject(result.get(i));
            JSONObject temp = new JSONObject();
            temp.put("type", goodsType[i]);
            temp.put("num", json.get("pieces"));
            temp.put("weight", json.get("weight"));
            temp.put("color", colors[i]);
            jsonArray.put(temp);
        }
        return jsonArray.toString();
    }

    public String efficient(Date end, int interval, String site) {
        JSONArray ewbResult = new JSONArray(ewbCount(end, interval, site));
        JSONArray attendanceRes = new JSONArray(attendance(end, interval, site));
        JSONArray result = new JSONArray();
        for(int i = 0; i < ewbResult.length(); i++) {
            JSONObject temp = new JSONObject();
            JSONObject ewbJson = (JSONObject)ewbResult.get(i);
            JSONObject attenJson = (JSONObject)attendanceRes.get(i);
            if(attenJson.getInt("loadNum") == 0) {
                temp.put("weight", 0);
                temp.put("num", 0);
            } else {
                temp.put("weight", ewbJson.getDouble("weight") / attenJson.getInt("loadNum"));
                temp.put("num", ewbJson.getDouble("num") / attenJson.getInt("loadNum"));
            }
            temp.put("date", ewbJson.get("date"));
            result.put(temp);
        }
        return result.toString();
    }

    public String siteRelation(Date end, int interval, String site) {

        if (!tools.getId2name().has(site)) {
            if (tools.getName2id().has(site)) {
                site = tools.getName2id().getString(site);
            } else {
                return new JSONArray().toString();
            }
        }
        Date start = tools.getStartTime(end, interval);
        String startTimestamp = tools.getTimeStamp(start);
        String endTimestamp = tools.getTimeStamp(end);

        String nextUrl = "http://202.120.117.179:8090/centerload/nextsiteload?siteId=" + site + "&start=" +
                startTimestamp + "&end=" + endTimestamp;
        String preUrl = "http://202.120.117.179:8090/centerunload/prevsiteload?siteId=" + site + "&start=" +
                startTimestamp + "&end=" + endTimestamp;

//        JSONArray nextResult = tools.request(nextUrl);
//        JSONArray preResult = tools.request(preUrl);

        ArrayList<String> urls = new ArrayList<String>();
        urls.add(nextUrl);
        urls.add(preUrl);
        ArrayList<String> results = tools.request(urls);
        JSONObject jsonObject = new JSONObject();

        for(int index = 0; index < results.size(); index++) {
            JSONArray result = new JSONArray(results.get(index));
            for(int i = 0; i < result.length(); i++) {
                JSONObject json = (JSONObject)result.get(i);
                System.out.println(json);
                if(tools.getId2name().has(String.valueOf(json.getInt("siteId"))))
                    json.put("siteId", tools.getId2name().get(String.valueOf(json.getInt("siteId"))));
            }
            if(index == 0) {
                jsonObject.put("next", result);
            } else {
                jsonObject.put("pre", result);
            }
        }
        return jsonObject.toString();
    }

}
